import 'dart:async';

import 'package:permission_handler/permission_handler.dart';
import 'package:kq_flutter_core_widget/utils/kq_sp_util.dart';
import 'package:kq_flutter_core_widget/utils/platform.dart';

import 'dialog_util.dart';

class PermissionUtils {
  PermissionUtils._inner();

  /// 获取权限授予状态
  static Future<PermissionStatus> status(Permission permission) {
    return permission.status;
  }

  /// 判断是否授予了权限
  static Future<bool> isGranted(Permission permission) {
    return permission.isGranted;
  }

  /// 进行权限申请
  ///
  /// [applyDesc]为权限申请前说明，[applyTitle]为权限申请前弹窗标题。
  ///
  /// [permanentlyDeniedDesc]表示权限被永久拒绝后的弹窗说明。
  ///
  /// [mapIosPermission]表示是否将受限权限，临时通知权限转化为granted，其它除永久拒绝权限转化为denied
  static Future<PermissionStatus> request(
    Permission permission, {
    String? applyDesc,
    String? applyTitle,
    String? permanentlyDeniedDesc,
    bool mapIosPermission = true,
  }) async {
    var isPermanentlyDenied =
        await PermissionUtils.isPermanentlyDenied(permission);
    if (isPermanentlyDenied) {
      if (permanentlyDeniedDesc == null) {
        return PermissionStatus.permanentlyDenied;
      }

      Completer<PermissionStatus> completer = Completer();
      KqDialog.showMsgDialog(
        msg: permanentlyDeniedDesc,
        onDismiss: () {
          completer.complete(PermissionStatus.permanentlyDenied);
        },
      );
      return completer.future;
    }

    if (applyDesc != null && PlatformEx.isAndroid) {
      var isGranted = await PermissionUtils.isGranted(permission);
      if (!isGranted) {
        Completer<PermissionStatus> completer = Completer();
        bool onTapConfirm = false;
        KqDialog.showConfirmDialog(
          title: applyTitle,
          msg: applyDesc,
          onConfirm: () {
            onTapConfirm = true;
            completer.complete(_request(permission, mapIosPermission));
          },
          onDismiss: () {
            if (!onTapConfirm) {
              completer.complete(PermissionStatus.denied);
            }
          },
        );
        return completer.future;
      }
    }

    return _request(permission, mapIosPermission);
  }

  /// 进行权限申请
  static Future<PermissionStatus> _request(
      Permission permission, bool mapIosPermission) async {
    var request = await permission.request();
    if (PlatformEx.isAndroid) {
      if (request == PermissionStatus.granted) {
        /// 如果给与了权限，则计数重置
        KqSpUtil.remove('isApplyPermission:${permission.toString()}');
      } else {
        // android平台申请过权限，则记录下来，用于后续判断是否永久拒绝权限
        KqSpUtil.setBool('isApplyPermission:${permission.toString()}', true);
      }
    } else if (mapIosPermission && PlatformEx.isIOS) {
      if (request == PermissionStatus.limited ||
          request == PermissionStatus.provisional) {
        // ios，如果是受限权限或临时通知权限，则当做给与了权限
        request = PermissionStatus.granted;
      } else if (request == PermissionStatus.restricted) {
        request = PermissionStatus.denied;
      }
    }
    return request;
  }

  /// 是否永久拒绝了权限
  static Future<bool> isPermanentlyDenied(Permission permission) async {
    if (PlatformEx.isAndroid) {
      if (permission == Permission.manageExternalStorage) {
        return false;
      }

      var isApply =
          KqSpUtil.getBool('isApplyPermission:${permission.toString()}');
      if (isApply != true) {
        return false;
      }

      var isGranted = await PermissionUtils.isGranted(permission);
      if (isGranted) {
        return false;
      }

      var should = await permission.shouldShowRequestRationale;
      return !should;
    } else {
      return permission.isPermanentlyDenied;
    }
  }
}
